package com.hyzh.latte.vehicle.nezha;

import cn.hutool.core.util.StrUtil;
import com.coffee.concurrent.CoffeeThreadFactory;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.Scheduler;
import com.hyzh.latte.vehicle.dmo.VehicleBO;
import com.hyzh.latte.vehicle.dmo.VehicleTrackDTO;
import lombok.Getter;

import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;


/**
 * @author: songkui
 * @since 2022-01-19
 */
public class VehicleCache {


    private final static long EXPIRE_TIME  = 60;
    //key: vehicleNo;
    @Getter
    private final Cache<String, VehicleBO> cache;
    @Getter
    private final String parkCode;

    public VehicleCache(String parkCode){
        cache = Caffeine.newBuilder()
                .removalListener(new VehicleExpireHandler())
                .expireAfterAccess(EXPIRE_TIME,  TimeUnit.SECONDS)
                .scheduler(Scheduler.forScheduledExecutorService(Executors.newScheduledThreadPool(1, new CoffeeThreadFactory("vehicle-cache"))))
                .build();

        this.parkCode = parkCode;
    }


    public VehicleBO getVehicle(String parkCode, VehicleTrackDTO trackDTO){
        VehicleBO vehicleBO = cache.getIfPresent(trackDTO.getVno());
        if (null != vehicleBO){
           if (null == vehicleBO.getObjectId() && StrUtil.isNotEmpty(trackDTO.getOid())){
                vehicleBO.setObjectId(trackDTO.getOid());
            }
            return vehicleBO;
        }

        vehicleBO = new VehicleBO(parkCode, trackDTO.getOid(), trackDTO.getVno(), trackDTO.getType());
        cache.put(vehicleBO.getVehicleNo(), vehicleBO);

        return vehicleBO;
    }

    public void removeVehicle(String vno){
        cache.invalidate(vno);
    }

    public long size(){
       return cache.estimatedSize();
    }

    public Map<String, VehicleBO> getAllEntries() {
        return cache.asMap();
    }

}
